package com.example.client;

import com.example.constant.MessageType;
import com.example.pojo.Header;
import com.example.pojo.NettyMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * <p>  </p>
 *
 * @author Chris
 * @since 2024/3/30 21:58
 */
public class HeartBeatReqHandler extends ChannelInboundHandlerAdapter {
    /**
     * 使用 slf4j 日志框架
     */
    private final static Logger log = LoggerFactory.getLogger(HeartBeatReqHandler.class);

    private volatile ScheduledFuture<?> HeartBeat;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        // 如果是握手应答消息，需要判断是否认证成功
        final NettyMessage message = (NettyMessage) msg;
        if (message.getHeader() != null
                && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
            // 握手成功，主动发送心跳消息
            ctx.executor().scheduleAtFixedRate(new HeartBeatReqHandler.HeartBeatTask(ctx),
                    0, 5000, TimeUnit.MILLISECONDS);
        } else if (message.getHeader() != null
                && message.getHeader().getType() == MessageType.HEARTBEAT_RESP.value()) {
            log.info("Client receive server heart beat message : ---> {}", message);
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("error=", cause);

        if (this.HeartBeat != null) {
            this.HeartBeat.cancel(true);
            this.HeartBeat = null;
        }

        ctx.fireExceptionCaught(cause);
    }

    private class HeartBeatTask implements Runnable {
        private final ChannelHandlerContext ctx;

        private HeartBeatTask(ChannelHandlerContext ctx) {
            this.ctx = ctx;
        }

        @Override
        public void run() {
            final NettyMessage heartBeat = this.buildHeartBeat();
            log.info("Client send heart beat message to server : ---> {}", heartBeat);
            ctx.writeAndFlush(heartBeat);
        }

        private NettyMessage buildHeartBeat() {
            final Header header = new Header();
            header.setType(MessageType.HEARTBEAT_REQ.value());

            final NettyMessage message = new NettyMessage();
            message.setHeader(header);
            return message;
        }

    }

}